import React, { useState, useEffect } from "react";
import {
  View,
  ScrollView,
  Alert,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
} from "react-native";
import { Text } from "~/components/ui/text";
import { Button } from "~/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import { useIroh, useFileTransfer } from "~/lib/iroh/hooks";
import { IrohUtils } from "~/lib/iroh/utils";

export default function IrohScreen() {
  const {
    node,
    documents,
    isInitialized,
    isLoading,
    error,
    initializeNode,
    createDocument,
    deleteDocument,
    shareDocument,
    receiveDocument,
    refreshDocuments,
    shutdown,
  } = useIroh();

  const { transfers, updateProgress } = useFileTransfer();
  const [newDocumentName, setNewDocumentName] = useState("");
  const [shareTicket, setShareTicket] = useState("");

  useEffect(() => {
    // Auto-initialize the node when the component mounts
    if (!isInitialized && !isLoading) {
      initializeNode();
    }
  }, [isInitialized, isLoading, initializeNode]);

  const handleCreateDocument = async () => {
    if (!newDocumentName.trim()) {
      Alert.alert("Error", "Please enter a document name");
      return;
    }

    const document = await createDocument(newDocumentName.trim());
    if (document) {
      setNewDocumentName("");
      Alert.alert(
        "Success",
        `Document "${document.name}" created successfully`,
      );
    }
  };

  const handleShareDocument = async (documentId: string) => {
    const ticket = await shareDocument(documentId);
    if (ticket) {
      Alert.alert(
        "Share Document",
        `Share this ticket with others to give them access to the document:\n\n${ticket}`,
        [
          {
            text: "Copy",
            onPress: () => {
              /* In real app, copy to clipboard */
            },
          },
          { text: "OK" },
        ],
      );
    }
  };

  const handleReceiveDocument = async () => {
    if (!shareTicket.trim()) {
      Alert.alert("Error", "Please enter a share ticket");
      return;
    }

    const transferId = `transfer_${Date.now()}`;

    const document = await receiveDocument(shareTicket.trim(), (progress) => {
      updateProgress(transferId, progress);
    });

    if (document) {
      setShareTicket("");
      Alert.alert(
        "Success",
        `Document "${document.name}" received successfully`,
      );
    }
  };

  const handleDeleteDocument = async (
    documentId: string,
    documentName: string,
  ) => {
    Alert.alert(
      "Delete Document",
      `Are you sure you want to delete "${documentName}"?`,
      [
        { text: "Cancel", style: "cancel" },
        {
          text: "Delete",
          style: "destructive",
          onPress: async () => {
            const success = await deleteDocument(documentId);
            if (success) {
              Alert.alert("Success", "Document deleted successfully");
            }
          },
        },
      ],
    );
  };

  return (
    <ScrollView className="flex-1 bg-background p-4">
      <View className="space-y-6">
        {/* Header */}
        <Card>
          <CardHeader>
            <CardTitle>Iroh P2P File Sharing</CardTitle>
            <CardDescription>
              Distributed file sharing powered by Iroh
            </CardDescription>
          </CardHeader>
        </Card>

        {/* Node Status */}
        <Card>
          <CardHeader>
            <CardTitle>Node Status</CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            {isLoading && (
              <View className="flex-row items-center space-x-2">
                <ActivityIndicator size="small" />
                <Text>Initializing node...</Text>
              </View>
            )}

            {error && <Text className="text-destructive">Error: {error}</Text>}

            {node && (
              <View className="space-y-1">
                <Text>Node ID: {node.id}</Text>
                <Text>
                  Status: {IrohUtils.getConnectionStatus(node.isConnected, 0)}
                </Text>
                <Text>Documents: {documents.length}</Text>
              </View>
            )}
          </CardContent>
        </Card>

        {/* Create Document */}
        {isInitialized && (
          <Card>
            <CardHeader>
              <CardTitle>Create Document</CardTitle>
              <CardDescription>
                Create a new document to share with others
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <TextInput
                value={newDocumentName}
                onChangeText={setNewDocumentName}
                placeholder="Enter document name"
                className="border border-border rounded-md px-3 py-2 text-foreground"
                placeholderTextColor="#666"
              />
              <Button
                onPress={handleCreateDocument}
                disabled={isLoading || !newDocumentName.trim()}
              >
                <Text>Create Document</Text>
              </Button>
            </CardContent>
          </Card>
        )}

        {/* Receive Document */}
        {isInitialized && (
          <Card>
            <CardHeader>
              <CardTitle>Receive Document</CardTitle>
              <CardDescription>
                Enter a share ticket to receive a document
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <TextInput
                value={shareTicket}
                onChangeText={setShareTicket}
                placeholder="Paste share ticket here"
                className="border border-border rounded-md px-3 py-2 text-foreground"
                placeholderTextColor="#666"
                multiline
                numberOfLines={3}
              />
              <Button
                onPress={handleReceiveDocument}
                disabled={isLoading || !shareTicket.trim()}
              >
                <Text>Receive Document</Text>
              </Button>
            </CardContent>
          </Card>
        )}

        {/* Document List */}
        {isInitialized && (
          <Card>
            <CardHeader>
              <CardTitle>My Documents</CardTitle>
              <CardDescription>Documents stored on this node</CardDescription>
            </CardHeader>
            <CardContent>
              {documents.length === 0 ? (
                <Text className="text-muted-foreground text-center py-4">
                  No documents yet. Create one above!
                </Text>
              ) : (
                <View className="space-y-3">
                  {documents.map((document) => (
                    <View
                      key={document.id}
                      className="border border-border rounded-md p-3"
                    >
                      <Text className="font-semibold">{document.name}</Text>
                      <Text className="text-sm text-muted-foreground">
                        Size: {IrohUtils.formatFileSize(document.size)}
                      </Text>
                      <Text className="text-sm text-muted-foreground">
                        Created: {document.created.toLocaleDateString()}
                      </Text>

                      <View className="flex-row space-x-2 mt-3">
                        <TouchableOpacity
                          onPress={() => handleShareDocument(document.id)}
                          className="bg-primary rounded px-3 py-1"
                          disabled={isLoading}
                        >
                          <Text className="text-primary-foreground text-sm">
                            Share
                          </Text>
                        </TouchableOpacity>

                        <TouchableOpacity
                          onPress={() =>
                            handleDeleteDocument(document.id, document.name)
                          }
                          className="bg-destructive rounded px-3 py-1"
                          disabled={isLoading}
                        >
                          <Text className="text-destructive-foreground text-sm">
                            Delete
                          </Text>
                        </TouchableOpacity>
                      </View>
                    </View>
                  ))}
                </View>
              )}

              <Button
                onPress={refreshDocuments}
                disabled={isLoading}
                variant="outline"
                className="mt-4"
              >
                <Text>Refresh List</Text>
              </Button>
            </CardContent>
          </Card>
        )}

        {/* Transfer Progress */}
        {transfers.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>File Transfers</CardTitle>
            </CardHeader>
            <CardContent>
              {transfers.map(([transferId, progress]) => (
                <View key={transferId} className="mb-3">
                  <Text className="text-sm">Transfer {transferId}</Text>
                  <View className="bg-muted rounded-full h-2 mt-1">
                    <View
                      className="bg-primary rounded-full h-2"
                      style={{ width: `${progress.percentage}%` }}
                    />
                  </View>
                  <Text className="text-xs text-muted-foreground mt-1">
                    {progress.percentage}% - {progress.status}
                  </Text>
                </View>
              ))}
            </CardContent>
          </Card>
        )}

        {/* Actions */}
        {isInitialized && (
          <Card>
            <CardHeader>
              <CardTitle>Node Actions</CardTitle>
            </CardHeader>
            <CardContent className="space-y-2">
              <Button
                onPress={shutdown}
                variant="destructive"
                disabled={isLoading}
              >
                <Text>Shutdown Node</Text>
              </Button>
            </CardContent>
          </Card>
        )}
      </View>
    </ScrollView>
  );
}

